#include <stdio.h> 
#include <stdlib.h> 
#include <malloc.h> 
#include <string.h>
#include <openssl/hmac.h> 
#include <openssl/evp.h> 
#include <openssl/engine.h> 
#include <openssl/aes.h>
#include <openssl/rand.h> 


#define SALT_LEN      16 //Salt长度16字节，由SN1和SN2拼接而成
#define PASS_LEN      32 //由云端分发
#define KEY_LEN       32 //KEY输出为32字节（16字节IV+16字节KEY）
#define ITERATION     1  //考虑到嵌入设备MCU性能，迭代次数为1

typedef signed int s32;
typedef unsigned char u8;
typedef signed char s8;

unsigned char salt_value[SALT_LEN]; 

void main() 
{ 
    s32 i=0; 
    s32 len =0; 
    u8 *out; 
    u8 *rspHMAC; 
    const s8 pwd[PASS_LEN] = "testtesttesttest"; 
    s8 rspPKCS5[KEY_LEN * 2]; 
    s32 ret; 

    rspHMAC = (unsigned char *) malloc(sizeof(char) * KEY_LEN); 
    out = (unsigned char *) malloc(sizeof(char) * KEY_LEN); 

    RAND_bytes(salt_value, SALT_LEN); 
	
	printf("pass value:\n");  
    for(i = 0; i < PASS_LEN; i++) { 
        printf("%02x", pwd[i]); 
    } 

    printf("\nsalt value:\n");  
    for(i = 0; i < SALT_LEN; i++) { 
        printf("%02x", salt_value[i]); 
    } 

    ret = PKCS5_PBKDF2_HMAC(pwd, strlen(pwd), salt_value, strlen(salt_value), ITERATION,EVP_sha256(), KEY_LEN, out); 

    printf("\nPKCS#5:\n"); 
    for(len = 0; len < KEY_LEN; len++){ 
        printf("%02x", out[len]);

        sprintf(&rspPKCS5[len * 2], "%02x", out[len]); 
    } 

    printf("\n"); 
} 